<template>
  <div class="task-config-tab">
    <!-- 搜索卡片 -->
    <div class="search-section">
      <el-card shadow="hover" class="search-card">
        <template #header>
          <div class="search-header">
            <div class="search-title">
              <el-icon><Search /></el-icon>
              <span>搜索与筛选</span>
            </div>
          </div>
        </template>

        <el-form :model="searchForm" class="search-form">
          <div class="search-form-content">
            <div class="search-form-fields">
              <el-form-item label="环境">
                <el-select
                  v-model="searchForm.env_id"
                  placeholder="选择环境"
                  clearable
                  style="width: 200px"
                >
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="env in store.envConfigsList"
                    :key="env.id"
                    :label="env.env_name"
                    :value="env.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="分类">
                <el-select
                  v-model="searchForm.category"
                  placeholder="选择分类"
                  clearable
                  filterable
                  style="width: 200px"
                >
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="cat in store.taskConfigCategories"
                    :key="cat"
                    :label="cat"
                    :value="cat"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="状态">
                <el-select
                  v-model="searchForm.status"
                  placeholder="选择状态"
                  clearable
                  style="width: 140px"
                >
                  <el-option label="全部" value="" />
                  <el-option label="活跃" value="active" />
                  <el-option label="暂停" value="paused" />
                  <el-option label="禁用" value="inactive" />
                </el-select>
              </el-form-item>

              <el-form-item label="监控状态">
                <el-select
                  v-model="searchForm.is_monitored"
                  placeholder="选择监控状态"
                  clearable
                  style="width: 140px"
                >
                  <el-option label="全部" value="" />
                  <el-option label="启用" :value="1" />
                  <el-option label="禁用" :value="0" />
                </el-select>
              </el-form-item>
            </div>

            <div class="search-form-actions">
              <el-button type="primary" @click="handleSearch" class="search-btn">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button type="warning" @click="handleReset" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button type="success" @click="handleCreate">
                <el-icon><Plus /></el-icon>
                新建配置
              </el-button>
            </div>
          </div>
        </el-form>
      </el-card>
    </div>

    <!-- 统计数据卡片 -->
    <div v-if="store.taskConfigsStats && Object.keys(store.taskConfigsStats).length > 0" class="stats-section">
      <el-card shadow="hover" class="stats-card">
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-label">总配置数</div>
            <div class="stat-value">{{ store.taskConfigsStats.total_count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">监控中</div>
            <div class="stat-value success">{{ store.taskConfigsStats.monitored_count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">告警启用</div>
            <div class="stat-value info">{{ store.taskConfigsStats.alert_enabled_count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">告警中</div>
            <div class="stat-value warning">{{ store.taskConfigsStats.alerting_count || 0 }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 表格卡片 -->
    <div class="table-section">
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <el-icon><List /></el-icon>
              <span>任务监控配置列表</span>
            </div>
            <div class="table-header-actions">
              <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="store.taskConfigsLoading" size="small">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <div class="table-info">
                <div class="pagination-control-wrapper clickable" @click="togglePagination">
                  <span class="page-count">本页 {{ store.taskConfigs.length }} 条</span>
                  <div class="divider"></div>
                  <span class="pagination-info">
                    {{ store.taskConfigsPage }}/{{ Math.ceil(store.taskConfigsTotal / store.taskConfigsPageSize) || 1 }}
                  </span>
                  <el-icon class="pagination-toggle-icon">
                    <ArrowUp v-if="paginationVisible" />
                    <ArrowDown v-else />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </template>

        <div class="table-container">
          <el-table
            :data="store.taskConfigs"
            v-loading="store.taskConfigsLoading"
            class="enhanced-table"
            style="width: 100%"
            :height="600"
            table-layout="fixed"
            :stripe="false"
            :border="false"
            @sort-change="handleSortChange"
          >
            <el-table-column prop="id" label="ID" width="80" sortable="custom" />
            <el-table-column label="环境" min-width="120" show-overflow-tooltip>
              <template #default="{ row }">
                {{ getEnvName(row.env_id) }}
              </template>
            </el-table-column>
            <el-table-column prop="category" label="分类" min-width="120" show-overflow-tooltip />
            <el-table-column prop="key_prefix" label="Key前缀" min-width="200" show-overflow-tooltip />
            <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>
              <template #default="{ row }">
                <span v-if="row.description">{{ row.description }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="is_monitored" label="监控" width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="row.is_monitored === 1 ? 'success' : 'info'" size="small">
                  {{ row.is_monitored === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="is_alert_enabled" label="告警" width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="row.is_alert_enabled === 1 ? 'warning' : 'info'" size="small">
                  {{ row.is_alert_enabled === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="alert_status" label="告警状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.alert_status === 'alerting'" type="danger" size="small">
                  告警中
                </el-tag>
                <el-tag v-else type="success" size="small">
                  正常
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleViewDetail(row)"
                      circle
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>

                  <el-tooltip content="编辑" placement="top">
                    <el-button
                      type="warning"
                      size="small"
                      @click="handleEdit(row)"
                      circle
                    >
                      <el-icon><Edit /></el-icon>
                    </el-button>
                  </el-tooltip>

                  <el-tooltip content="删除" placement="top">
                    <el-button
                      type="danger"
                      size="small"
                      @click="handleDelete(row)"
                      circle
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <transition name="pagination-slide">
          <div v-show="paginationVisible" class="pagination-section">
            <el-pagination
              v-model:current-page="store.taskConfigsPage"
              v-model:page-size="store.taskConfigsPageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="store.taskConfigsTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              background
            />
          </div>
        </transition>
      </el-card>
    </div>

    <!-- 任务配置对话框 -->
    <TaskConfigDialog
      v-model="dialogVisible"
      :task-config="currentTaskConfig"
      :mode="dialogMode"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search, Refresh, Plus, List, View, Edit, Delete,
  ArrowUp, ArrowDown
} from '@element-plus/icons-vue'
import { useRedisTaskMonitorStore } from '@/stores/redisTaskMonitor'
import TaskConfigDialog from './dialogs/TaskConfigDialog.vue'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('TaskConfigTab')
const store = useRedisTaskMonitorStore()

const searchForm = reactive({
  env_id: '',
  category: '',
  status: '',
  is_monitored: ''
})

const paginationVisible = ref(true)
const dialogVisible = ref(false)
const dialogMode = ref('create')
const currentTaskConfig = ref(null)
const sortField = ref('last_alert_time')
const sortOrder = ref('desc')

// 获取环境名称
const getEnvName = (envId) => {
  const env = store.envConfigsList.find(e => e.id === envId)
  return env ? env.env_name : `环境${envId}`
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    active: 'success',
    paused: 'warning',
    inactive: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    active: '活跃',
    paused: '暂停',
    inactive: '禁用'
  }
  return statusMap[status] || status
}

// 搜索
const handleSearch = async () => {
  store.taskConfigsPage = 1
  await fetchData()
}

// 重置
const handleReset = () => {
  searchForm.env_id = ''
  searchForm.category = ''
  searchForm.status = ''
  searchForm.is_monitored = ''
  store.taskConfigsPage = 1
  fetchData()
}

// 刷新
const handleRefresh = () => {
  fetchData()
}

// 创建
const handleCreate = () => {
  currentTaskConfig.value = null
  dialogMode.value = 'create'
  dialogVisible.value = true
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const data = await store.fetchTaskConfig(row.id)
    currentTaskConfig.value = data
    dialogMode.value = 'view'
    dialogVisible.value = true
  } catch (error) {
    componentLogger.error('获取任务配置详情失败', error)
  }
}

// 编辑
const handleEdit = async (row) => {
  try {
    const data = await store.fetchTaskConfig(row.id)
    currentTaskConfig.value = data
    dialogMode.value = 'edit'
    dialogVisible.value = true
  } catch (error) {
    componentLogger.error('获取任务配置详情失败', error)
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务配置 "${row.key_prefix}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await store.deleteTaskConfig(row.id)
    ElMessage.success('删除成功')
    await fetchData()
    emit('stats-updated')
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('删除任务配置失败', error)
    }
  }
}

// 排序
const handleSortChange = ({ prop, order }) => {
  if (prop) {
    sortField.value = prop
    sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
    fetchData()
  }
}

// 分页
const handleSizeChange = (size) => {
  store.taskConfigsPageSize = size
  store.taskConfigsPage = 1
  fetchData()
}

const handlePageChange = (page) => {
  store.taskConfigsPage = page
  fetchData()
}

const togglePagination = () => {
  paginationVisible.value = !paginationVisible.value
}

// 对话框成功回调
const handleDialogSuccess = () => {
  fetchData()
  emit('stats-updated')
}

// 获取数据
const fetchData = async () => {
  try {
    const params = {
      page: store.taskConfigsPage,
      pageSize: store.taskConfigsPageSize,
      sort: sortField.value,
      order: sortOrder.value
    }

    if (searchForm.env_id) {
      params.env_id = searchForm.env_id
    }

    if (searchForm.category) {
      params.category = searchForm.category
    }

    if (searchForm.status) {
      params.status = searchForm.status
    }

    if (searchForm.is_monitored !== '') {
      params.is_monitored = searchForm.is_monitored
    }

    await store.fetchTaskConfigs(params)
  } catch (error) {
    componentLogger.error('获取任务配置列表失败', error)
  }
}

// 导出方法供父组件调用
defineExpose({
  fetchData
})

const emit = defineEmits(['stats-updated'])

onMounted(async () => {
  // 加载环境列表
  await store.fetchEnvConfigsList()
  // 加载分类列表
  await store.fetchTaskConfigCategories()
  // 加载数据
  await fetchData()
})
</script>

<style scoped>
.task-config-tab {
  padding: 0;
}

.search-section {
  margin-bottom: 20px;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.info {
  color: #409eff;
}

.stat-value.warning {
  color: #f56c6c;
}

.search-card,
.table-card {
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.search-form {
  margin-top: 0;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form-fields {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  flex: 1;
}

.search-form-actions {
  display: flex;
  gap: 10px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.table-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.pagination-control-wrapper:hover {
  background-color: #f5f7fa;
}

.page-count {
  font-size: 12px;
  color: #606266;
}

.divider {
  width: 1px;
  height: 14px;
  background-color: #dcdfe6;
}

.pagination-info {
  font-size: 12px;
  color: #909399;
}

.pagination-toggle-icon {
  font-size: 12px;
  color: #909399;
}

.table-container {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

.pagination-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s ease;
}

.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>

